<?php
/**
 * Metadata Dao definition
 *
 * @author fusq
 * @since 2009-03-25
 */

require_once BaseUtil::getModulePath ( "base" ) . '/models/BaseDao.php';

class MetadataDao extends BaseDao {
	
	protected $_name;
	
	protected $metadataGroup;
	
	protected $metadataSet;
	
	public function _setup() {
		$this->_name = $this->prefix () . "metadatas";
		$this->metadataGroup = $this->prefix () . "metadata_groups";
		$this->metadataSet = $this->prefix () . "metadata_sets";
		parent::_setup ();
	}
	
	public function insertMetadata($data) {
		return $this->insertData ( $data );
	}
	
	public function updateMetadata($data, $id) {
		$where = $this->getAdapter ()->quoteInto ( 'id = ?', $id );
		$this->updateData ( $data, $where );
	}
	
	public function getMetadata($id) {
		return $this->getByCol ( "id", $id );
	}
	
	public function getMetadataBySet($setId, $type) {
		$select = $this->db_r->select ();
		$select->from ( $this->_name, "*" );
		$select->join ( $this->metadataGroup, $this->metadataGroup . ".id = " . $this->_name . ".group_id", array ("metadata_set_id" ) );
		$select->join ( $this->metadataSet, $this->metadataSet . ".id = " . $this->metadataGroup . ".metadata_set_id", array ("id as set_id" ) );
		$select->where ( $this->_name . ".type = ?", $type );
		$select->where ( $this->_name . ".is_delete = 0" );
		$select->where ( $this->metadataSet . ".id = ?", $setId );
		$select->order ( $this->_name . ".sort_order ASC" );
		$sql = $select->__toString ();
		$result = $this->db_r->fetchAll ( $sql );
		return $result;
	}
	
	public function getMetadataByGroupId($groupId) {
		return $this->db_r->fetchAll ( "select 	* 
    									from 	$this->_name 
    									where 	group_id = $groupId 
    									and 	is_delete = 0
    									order	by sort_order" );
	}
	
	public function getMetedataByIds($idArray) {
		$result = array ();
		$ids = implode ( ",", $idArray );
		$select = $this->db_r->select ();
		$select->from ( $this->_name, "*" );
		$select->where ( "id in ($ids)" );
		$select->where ( "is_delete = 0" );
		$sql = $select->__toString ();
		$metadatas = $this->db_r->fetchAll ( $sql );
		if (! empty ( $metadatas )) {
			foreach ( $metadatas as $metadata ) {
				$result [$metadata ['id']] = $metadata;
			}
		}
		return $result;
	}
	
	public function getMaxOrder($groupId) {
		return $this->db_r->fetchRow ( "select 	max(sort_order) num
    									from 	$this->_name 
    									where 	group_id = $groupId 
    									and 	is_delete = 0" );
	}
}